package br.gov.serpro.curso.projeto.wishlist;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ListView;
import br.gov.serpro.curso.projeto.adapter.ExpAdapter;
import br.gov.serpro.curso.projeto.http.HttpUtil;
import br.gov.serpro.curso.projeto.wishilist.servicos.Servico;
import br.serpro.curso.projeto.db.DBOpenHelper;

public class ListaActivity extends Activity {

	DisplayMetrics metrics;
	int width;
	ExpandableListView expList;
	
	ListView listView;
	
	PendingIntent pendingIntent;
	
	Button button;
	
	/**
	 * strings for child elements
	 */
	public static ArrayList<ArrayList<String>> arrChildElements;
	
	/**
	 * strings for group elements
	 */
	public static ArrayList<String> arrGroupElements;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lista);
	}
	
	private String precoProduto(final String produto){
		
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				String preco = "";
				String strjson = HttpUtil.doGet("http://sandbox.buscape.com/service/findProductList/72577349624e6c685068513d/?keyword=keyword&format=json");
				try {
					JSONObject jsonobj = new JSONObject(strjson);
					JSONArray jsonArray = jsonobj.getJSONArray("product");
					
					for(int index=0; index < jsonArray.length(); index++){
						JSONObject jsonObject = jsonArray.getJSONObject(index);
						JSONObject jsonProduct = jsonObject.getJSONObject("product");
						if(jsonProduct.getString("productname").equalsIgnoreCase(produto)) {
							preco = jsonProduct.getString("productname") +" - "+ (jsonProduct.getString("pricemin") != null ?jsonProduct.getString("pricemin") : "");
						}
					}					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return preco;
			}

			@Override
			protected void onPostExecute(String result) {
				Intent intent = new Intent(ListaActivity.this, Servico.class);
				intent.putExtra("preco", result);
				startService(intent);
			}
		}.execute();		
		return null;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		listView = (ListView) findViewById(R.id.lv_lista);
		/**/
		new AsyncTask<Void, Void, ArrayAdapter<String>>() {

			final ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListaActivity.this,
					android.R.layout.simple_list_item_1, android.R.id.text1);
			@Override
			protected ArrayAdapter<String> doInBackground(Void... params) {
				String strjson = HttpUtil.doGet("http://sandbox.buscape.com/service/findProductList/72577349624e6c685068513d/?keyword=keyword&format=json");
				try {
					JSONObject jsonobj = new JSONObject(strjson);
					JSONArray jsonArray = jsonobj.getJSONArray("product");
					
					for(int index=0; index < jsonArray.length(); index++){
						JSONObject jsonObject = jsonArray.getJSONObject(index);
						JSONObject jsonProduct = jsonObject.getJSONObject("product");
						adapter.add(jsonProduct.getString("productname") +" - "+ jsonProduct.getString("pricemin"));
						Log.i("BUSCA", jsonProduct.getString("productname"));
					}					
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return adapter;
				
			}

			@Override
			protected void onPostExecute(ArrayAdapter<String> result) {
					listView.setAdapter(result);
			}
		}.execute();
		/**********************************/

		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String p = precoProduto("Keyword Intelligence: Keyword Research for Search, Social, and Beyond - cod: 9781118216910");

				//pendingIntent = PendingIntent.getService(ListaActivity.this, 0, intent, 0);
				//AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				//alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 1000,
				//		pendingIntent);
			}

		});
			
		arrGroupElements = new ArrayList<String>();
		arrChildElements = new ArrayList<ArrayList<String>>();
		expList = (ExpandableListView) findViewById(R.id.elv_lista);

		Cursor cursor = DBOpenHelper.queryCategorias();

		while (cursor.moveToNext()) {
			arrGroupElements.add(cursor.getString(0));
			//Cursor c = DBOpenHelper.db.query(DBOpenHelper.ITEM_TABELA, new String[]{"categoria", "nome"}, "categoria = ?", new String[]{cursor.getString(0)}, "categoria", null, "categoria");
			
			Cursor c = DBOpenHelper.db.rawQuery("select categoria, nome from item where categoria = ?", new String[]{cursor.getString(0)});
			
			Log.i("LISTA", "CAT: "+cursor.getString(0));
			ArrayList<String> arrayListChild = new ArrayList<String>();
			while (c.moveToNext()) {
				Log.i("LISTA", "ITEM: "+c.getString(0)+" "+c.getString(1));
				arrayListChild.add(c.getString(1));
			}
			c.close();	
			arrChildElements.add(arrayListChild);
		}
		cursor.close();
		
	
		
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		width = metrics.widthPixels;
		
		// this code for adjusting the group indicator into right side of the view
		expList.setIndicatorBounds(width - getDipsFromPixel(50), width - getDipsFromPixel(10));
		expList.setAdapter(new ExpAdapter(this));

		expList.setOnGroupExpandListener(new OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int groupPosition) {
				Log.e("onGroupExpand", "OK");
			}
		});

		expList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			@Override
			public void onGroupCollapse(int groupPosition) {
				Log.e("onGroupCollapse", "OK");
			}
		});

		expList.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				Log.e("OnChildClickListener", "OK");
				return false;
			}
		});
		
	}
	
	public int getDipsFromPixel(float pixels) {
		// Get the screen's density scale
		final float scale = getResources().getDisplayMetrics().density;
		// Convert the dps to pixels, based on density scale
		return (int) (pixels * scale + 0.5f);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_lista, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_novo:
			Intent intent = new Intent(ListaActivity.this,	CadastroActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
